<?php
require_once("../data/common.php");

//TODO: Allow users to load only their own tracks with the following exceptions:
// -The track is marked public

header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
Header("Content-type: application/vnd.google-earth.kml+xml");
# Header("Content-type: text/plain");

$template = new STE();
$template->load("track");

	# $sql = "SELECT time_received, lat, lon, speed, alt, hdop FROM gps_data WHERE ( hdop <= 2  OR hdop is null) AND device_id = ? AND id BETWEEN ? AND ? ORDER BY time_received;";


	# need to check whether user has enough privileges to see this track.. currently this is a security hole..
	# $sql = "SELECT * FROM tracks WHERE id = ?";
	# $stmt = $dbh->prepare($sql);
	# $stmt->execute(array($_GET["track_id"]));
	# $row = $stmt->fetch();
	# $stmt = null;

	$sql = "SELECT time_received, lat, lon, speed, alt, hdop FROM gps_data WHERE device_id = ? AND id BETWEEN ? AND ? ORDER BY time_received;";
	$stmt = $dbh->prepare($sql);
	$stmt->execute(array($_GET["device_id"],$_GET["first_id"],$_GET["last_id"]));

	$variables["COORDINATES"] = "";
	$rows = $stmt->fetchAll();
	$counter = 0;
	$distance = 0;
	$last_lat = 0;
	$last_lon = 0;
	$average_speed = 0;
	$max_speed = 0;
	$max_alt = 0;
	$min_alt = 0;
	$start_time = "";
	foreach ($rows as $rs) {
		$variables["COORDINATES"] .= sprintf("\t\t%f,%f\n",$rs["lon"],$rs["lat"]);
		if ($counter > 0) {
			$distance += distance($rs["lat"], $rs["lon"], $last_lat, $last_lon);
			$average_speed = $average_speed+$rs["speed"];
			if ($rs["speed"] > $max_speed) $max_speed = $rs["speed"];
			if ($rs["alt"] > $max_alt) $max_alt = $rs["alt"];
			if ($rs["alt"] < $min_alt) $min_alt = $rs["alt"];
		} else {
			$start_time = $rs["time_received"];
			$average_speed = $rs["speed"];
			$max_speed = $average_speed;
			$max_alt = $rs["alt"];
			$min_alt = $max_alt;
		}

		$last_lat = $rs["lat"];
		$last_lon = $rs["lon"];
		$end_time = $rs["time_received"];
		$counter++;
	}
	$average_speed = $average_speed/($counter-1);
	$variables["DISTANCE"] = round($distance,1);
	$variables["MAX_SPEED"] = round((1.852*$max_speed),2); //Knots to km/h
	$variables["AVG_SPEED"] = round((1.852*$average_speed),2); 
	$variables["MAX_ALT"] = $max_alt; 
	$variables["MIN_ALT"] = $min_alt;
	$variables["START_TIME"] = $start_time." UTC";
	$variables["END_TIME"] = $end_time." UTC";

	$variables["TRACK_NAME"] = strftime("%Y-%m-%d %H:%I",time());
	
	$template->assign($variables);
	print $template->display();

?>
